﻿namespace TfsReportRenderer.ImageAdder
{
    using System.Drawing;

    /// <summary>
    /// The image positioning helper for EMU.
    /// EMU (english metrical unit) is the smallest useful unit of measure and is used by VML for internal unit storage. There are 914400 EMU per inch and 12700 EMU in a point. EMUs cannot be fractional..
    /// See: <a href="http://user239.blogspot.de/2011/03/how-to-insert-image-to-excel-document.html"> How to insert an image into an Excel document </a>
    /// </summary>
    public class ImagePositioningEmu
    {
        private readonly int _maxWidth;

        private readonly int _maxHeight;

        private readonly int _width;
        
        private readonly int _height;

        private readonly int _offsetX;
        
        private readonly int _offsetY;

        private readonly float _verticalResolution;
        
        private readonly float _horizontalResolution;

        public int MaxWidth
        {
            get { return ConvertToEmu(this._maxWidth, this._horizontalResolution); }
        }

        public int MaxHeight
        {
            get { return ConvertToEmu(this._maxHeight, this._verticalResolution); }
        }

        public int Width
        {
            get { return ConvertToEmu(this._width, this._horizontalResolution); }
        }

        public int Height
        {
            get { return ConvertToEmu(this._height, this._verticalResolution); }
        }

        public int OffsetX
        {
            get { return ConvertToEmu(this._offsetX, this._horizontalResolution); }
        }

        public int OffsetY
        {
            get { return ConvertToEmu(this._offsetY, this._verticalResolution); }
        }

        private static int ConvertToEmu(int pixels, float resolution)
        {
            return (int)(914400 * pixels / resolution);
        }

        public ImagePositioningEmu(string imageFileName, int maxWidth, int maxHeight, int offsetX, int offsetY)
        {
            this._maxWidth = maxWidth;
            this._maxHeight = maxHeight;
            this._offsetX = offsetX;
            this._offsetY = offsetY;

            using (var bitmap = new Bitmap(imageFileName))
            {
                this._width = bitmap.Width;
                this._height = bitmap.Height;
                this._horizontalResolution = bitmap.HorizontalResolution;
                this._verticalResolution = bitmap.VerticalResolution;
            }
        }
    }
}